import React, { Component } from 'react';
import { Button, Modal, Select, Form, Row, Col, Input, Radio, DatePicker, message } from 'antd';
import { connect } from 'dva';
import BaseComponent from '@/components/BaseComponent';
import moment from 'moment';

@connect(({ user }) => ({
  // data: risk.riskData,
  currentUser: user.currentUser,
}))
class index extends BaseComponent {
  state = {
    visible: false,
    form: {},
    provinceIdData: [],
    cityIdData: [],
    districtIdData: [],
    institutionIdData: [],
  };

  provinceIdChange = value => {
    const str = value ? this.state.provinceIdData.find(item => item.code == value) : '';
    const name = str.name;
    this.setState(
      params => ({
        form: {
          ...params.form,
          provinceId: value,
          province: name,
        },
      }),
      () => {
        this.getCity({ level: 2, parentCode: value });
      }
    );
  };
  cityIdChange = value => {
    const str = value ? this.state.cityIdData.find(item => item.code == value) : '';
    const name = str.name;
    this.setState(
      params => ({
        form: {
          ...params.form,
          cityId: value,
          city: name,
        },
      }),
      () => {
        this.getCity({ level: 3, parentCode: value });
      }
    );
  };

  districtIdChange = value => {
    const str = value ? this.state.districtIdData.find(item => item.code == value) : '';
    const name = str.name;
    this.setState(
      params => ({
        form: {
          ...params.form,
          districtId: value,
          district: name,
        },
      }),
      () => {
        this.listAllData(value);
      }
    );
  };

  institutiChange = value => {
    const str = value ? this.state.institutionIdData.find(item => item.id == value) : '';
    const name = str.org_name;
    this.setState(params => ({
      form: {
        ...params.form,
        institutionId: value,
        institution: name,
      },
    }));
  };

  screeningYearChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        screeningYear: value,
      },
    }));
  };

  firstScreeningTaskVolumeChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        firstScreeningTaskVolume: value,
      },
    }));
  };
  followTaskVolumeChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        followTaskVolume: value,
      },
    }));
  };
  yearTaskVolumeChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        yearTaskVolume: value,
      },
    }));
  };
  approvedDetectionRateChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        approvedDetectionRate: value,
      },
    }));
  };
  timeBeginChange = (date, dateString) => {
    console.log(date, dateString);
    this.setState(params => ({
      form: {
        ...params.form,
        timeBegin: dateString,
      },
    }));
  };
  timeEndChange = (date, dateString) => {
    console.log(date, dateString);
    this.setState(params => ({
      form: {
        ...params.form,
        timeEnd: dateString,
      },
    }));
  };

  showModal = () => {
    this.getCity({ level: 1, parentCode: '1' });
    this.setState({
      visible: true,
    });
  };

  handleOk = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const { form } = this.state;
        this.execHttp('taskAllocation/add', {
          ...form,
        }).then(resp => {
          if (resp && resp.success) {
            message.success(resp.message);
            this.handleCancel();
            this.props.getDataByPage({});
          } else if (resp && resp.success === false) {
            message.error(resp.message);
            this.handleCancel();
          }
        });
      }
    });
  };

  handleCancel = () => {
    this.props.form.resetFields();
    this.setState({
      visible: false,
      form: {},
    });
  };

  // 查询省
  getCity = param => {
    this.execHttp('plannedFollowUp/getCity', { ...param }).then(resp => {
      if (resp) {
        if (param.level == 1) {
          this.setState({
            provinceIdData: resp.data,
          });
        } else if (param.level == 2) {
          this.setState({
            cityIdData: resp.data,
          });
        } else if (param.level == 3) {
          this.setState({
            districtIdData: resp.data,
          });
        } else if (param.level == 4) {
          this.setState({
            countyIdData: resp.data,
          });
        } else if (param.level == 5) {
          this.setState({
            villageIdData: resp.data,
          });
        }
      }
    });
  };

  /** 点击获取机构 */
  listAllData = val => {
    this.execHttp('taskAllocation/listAllData', {
      currentPage: 1,
      pageSize: 9999,
      region_name: val,
      user: this.props.currentUser.id,
    }).then(resp => {
      if (resp && resp.success) {
        this.setState({
          institutionIdData: resp.data.list,
        });
      }
    });
  };

  render() {
    const { visible } = this.state;
    const { getFieldDecorator } = this.props.form;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };

    return (
      <div>
        <Button type="primary" onClick={this.showModal}>
          添加
        </Button>
        <Modal
          title="新增"
          visible={visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          width={1200}
        >
          <h3>基本信息</h3>
          <Form {...formItemLayout}>
            <Row gutter={16}>
              <Col span={8}>
                <Form.Item label="所属省份">
                  {getFieldDecorator('provinceId', {
                    rules: [{ required: true, message: '所属省份不能为空' }],
                  })(
                    <Select
                      allowClear
                      onChange={this.provinceIdChange}
                      style={{ width: 200 }}
                      placeholder="请选择所属省份"
                    >
                      {this.state.provinceIdData.map(item => (
                        <Select.Option key={item.code} value={item.code}>
                          {item.name}
                        </Select.Option>
                      ))}
                    </Select>
                  )}
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="所属城市">
                  {getFieldDecorator('cityId', {
                    rules: [{ required: true, message: '所属城市不能为空' }],
                  })(
                    <Select
                      allowClear
                      onChange={this.cityIdChange}
                      style={{ width: 200 }}
                      placeholder="请选择所属城市"
                    >
                      {this.state.cityIdData.map(item => (
                        <Select.Option key={item.code} value={item.code}>
                          {item.name}
                        </Select.Option>
                      ))}
                    </Select>
                  )}
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="所属区/县">
                  {getFieldDecorator('districtId', {
                    rules: [{ required: true, message: '所属区/县不能为空' }],
                  })(
                    <Select
                      allowClear
                      onChange={this.districtIdChange}
                      style={{ width: 200 }}
                      placeholder="请选择所属区/县"
                    >
                      {this.state.districtIdData.map(item => (
                        <Select.Option key={item.code} value={item.code}>
                          {item.name}
                        </Select.Option>
                      ))}
                    </Select>
                  )}
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={16}>
              <Col span={8}>
                <Form.Item label="所属机构">
                  {getFieldDecorator('institutionId', {
                    rules: [{ required: true, message: '所属机构不能为空' }],
                  })(
                    <Select
                      allowClear
                      onChange={this.institutiChange}
                      showSearch
                      filterOption={(input, option) =>
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      }
                      style={{ width: 200 }}
                      placeholder="请选择所属机构"
                    >
                      {this.state.institutionIdData.map(item => (
                        <Select.Option key={item.id} value={item.id}>
                          {item.org_name}
                        </Select.Option>
                      ))}
                    </Select>
                  )}
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="筛查年度">
                  {getFieldDecorator('screeningYear', {
                    rules: [{ required: true, message: '筛查年度不能为空' }],
                  })(
                    <Input
                      placeholder="筛查年度"
                      onChange={this.screeningYearChange}
                      style={{ width: 200 }}
                    />
                  )}
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="初筛任务量(人)">
                  {getFieldDecorator('firstScreeningTaskVolume', {
                    rules: [{ required: true, message: '初筛任务量不能为空' }],
                  })(
                    <Input
                      placeholder="初筛任务量(人)"
                      onChange={this.firstScreeningTaskVolumeChange}
                      style={{ width: 200 }}
                    />
                  )}
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={16}>
              <Col span={8}>
                <Form.Item label="随访任务量(人)">
                  {getFieldDecorator('followTaskVolume', {
                    rules: [{ required: true, message: '随访任务量不能为空' }],
                  })(
                    <Input
                      placeholder="随访任务量(人)"
                      onChange={this.followTaskVolumeChange}
                      style={{ width: 200 }}
                    />
                  )}
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="年度任务量(人)">
                  {getFieldDecorator('yearTaskVolume', {
                    rules: [{ required: true, message: '年度任务量不能为空' }],
                  })(
                    <Input
                      placeholder="年度任务量(人)"
                      onChange={this.yearTaskVolumeChange}
                      style={{ width: 200 }}
                    />
                  )}
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="核定检出率(%)">
                  {getFieldDecorator('approvedDetectionRate', {
                    rules: [
                      { required: true, message: '核定检出率不能为空' },
                      {
                        pattern: /^[0-9]*(\.[0-9]*)?$/,
                        message: '请输入有效的数字或小数',
                      },
                    ],
                  })(
                    <Input
                      placeholder="核定检出率"
                      onChange={this.approvedDetectionRateChange}
                      style={{ width: 200 }}
                    />
                  )}
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={16}>
              <Col span={8}>
                <Form.Item label="起始日期">
                  {getFieldDecorator('timeBegin', {
                    rules: [{ required: true, message: '起始日期不能为空' }],
                  })(
                    <DatePicker
                      style={{ width: 200 }}
                      showTime
                      format="YYYY-MM-DD"
                      onChange={this.timeBeginChange}
                    />
                  )}
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="结束日期">
                  {getFieldDecorator('timeEnd', {
                    rules: [{ required: true, message: '结束日期不能为空' }],
                  })(
                    <DatePicker
                      style={{ width: 200 }}
                      showTime
                      format="YYYY-MM-DD"
                      onChange={this.timeEndChange}
                    />
                  )}
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </Modal>
      </div>
    );
  }
}

const WrappedMyForm = Form.create()(index);

export default WrappedMyForm;
